package com.example.ecbanner;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by r on 2017/5/24.
 */

public class CycleBannerView extends RelativeLayout implements GestureDetector.OnGestureListener{

    public static final int PERIOD = 5000;

    private Context mContext;
    private Animation leftInAnimation;
    private Animation leftOutAnimation;
    private Animation rightInAnimation;
    private Animation rightOutAnimation;
    private GestureDetector detector; // 手势检测
    boolean mLeftOrRight = true;// 自动循环的方向
    private ViewFlipper mViewFlipper;
    private LinearLayout mDotLine; // 圆点标识
    public ImageView safe_img;

    private ArrayList<ImageView> mImgList;// 以后扩展注意修改list的泛型


    private ArrayList<ImageView> mImgViewList = new ArrayList<ImageView>();
    private List<ImageView> dots = new ArrayList<ImageView>();
    private int page_focused = R.drawable.page_focused;
    private int page_unfocused = R.drawable.page_unfocused;
    private static final int RECORD_TIMER = 8112;
    private static final int RECORD_DONE = 8113;
    private int mRecordTime = 0;
    private boolean isRecoding = false;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    public TimerHandler mTimerHandler = new TimerHandler(this);
    protected boolean onStarting = false;

    private void startFlipBanner() {
        mRecordTime = 0;
        if (mTimer == null)
            mTimer = new Timer();
        if (mTimerTask == null) {
            mTimerTask = new RecordTimeTask();
            mTimer.schedule(mTimerTask, 0, PERIOD);
        }
        isRecoding = true;

    }

    public static class TimerHandler extends Handler {
        WeakReference<CycleBannerView> reference;

        public TimerHandler(CycleBannerView view) {
            reference = new WeakReference<CycleBannerView>(view);
        }

        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case RECORD_TIMER:
                    if (reference != null && reference.get() != null) {
                        if (reference.get().mLeftOrRight) {
                            reference.get().toRight();// 向右滑动
                        } else {
                            reference.get().toLeft();// 向左滑动
                        }
                    }
                    break;
                case RECORD_DONE:
                    break;
                default:
                    break;
            }
        }
    }

    private class RecordTimeTask extends TimerTask {
        @Override
        public void run() {
            if (isRecoding) {
                mRecordTime++;
                Message message = new Message();
                message.what = RECORD_TIMER;
                message.obj = mRecordTime;
                mTimerHandler.sendMessage(message);
            }

        }
    }

    public void setDots(int focused, int unfocused) {
        page_focused = focused;
        page_unfocused = unfocused;
    }

    /**
     * @param context
     */
    public CycleBannerView(Context context) {
        super(context);
        init(context);
    }

    /**
     * @param context
     * @param attrs
     */
    public CycleBannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);

    }

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    public CycleBannerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    /**
     * init:(初始化操作). <br/>
     *
     * @author askzhao
     */
    private void init(Context context) {

        mContext = context;
        View mContentView = RelativeLayout.inflate(mContext,
                R.layout.cycle_banner_layout, null);
        android.view.ViewGroup.LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(mContentView, params);
        safe_img = (ImageView) findViewById(R.id.safe_img);

        mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
        mDotLine = (LinearLayout) findViewById(R.id.dot_line);
        detector = new GestureDetector(this);

        // 动画效果
        leftInAnimation = AnimationUtils
                .loadAnimation(mContext, R.anim.left_in);
        leftOutAnimation = AnimationUtils.loadAnimation(mContext,
                R.anim.left_out);
        rightInAnimation = AnimationUtils.loadAnimation(mContext,
                R.anim.right_in);
        rightOutAnimation = AnimationUtils.loadAnimation(mContext,
                R.anim.right_out);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        detector.onTouchEvent(event); // touch事件交给手势处理。
        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                           float velocityY) {
        if (mImgList.size() != 1)
            if (e1.getX() - e2.getX() > 120) {
                toRight();
                return true;
            } else if (e1.getX() - e2.getX() < -120) {
                toLeft();
                return true;
            }
        return false;
    }

    public void toRight() {

        mViewFlipper.setInAnimation(leftInAnimation);
        mViewFlipper.setOutAnimation(leftOutAnimation);
        int position = mViewFlipper.getDisplayedChild();
        if (dots != null && dots.size() > position)
            dots.get(position).setBackgroundResource(page_unfocused);
        mViewFlipper.showNext();// 向右滑动
        position = mViewFlipper.getDisplayedChild();
        if (dots != null && dots.size() > position)
            dots.get(position).setBackgroundResource(page_focused);
        mLeftOrRight = true;
    }

    public void toLeft() {
        mViewFlipper.setInAnimation(rightInAnimation);
        mViewFlipper.setOutAnimation(rightOutAnimation);
        int position = mViewFlipper.getDisplayedChild();
        if (dots != null && dots.size() > position)
            dots.get(position).setBackgroundResource(page_unfocused);
        mViewFlipper.showPrevious();// 向左滑动
        position = mViewFlipper.getDisplayedChild();
        if (dots != null && dots.size() > position)
            dots.get(position).setBackgroundResource(page_focused);
        mLeftOrRight = false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
                            float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
//        int position = mViewFlipper.getDisplayedChild();
//        try {
//            String url = mImgList.get(position).getUrl();
//            if (!TextUtils.isEmpty(url)) {
//                SystemUtils.onEvent("Regular_Banner_" + (position + 1), 1);
//                Intent intent = new Intent(mContext, KKDWebActivity.class);
//                intent.putExtra("useTitleName", true);
//                intent.putExtra("titleName", mImgList.get(position).getTitle());
//                intent.putExtra("desc", mImgList.get(position).getDesc());
//                intent.putExtra("url", url);
//                intent.putExtra("shareUrl", mImgList.get(position)
//                        .getShareUrl());
//                mContext.startActivity(intent);
//            }
//        } catch (Exception e1) {
//            e1.printStackTrace();
//        }

        return false;
    }

    /**
     * recycle:(当actvity退出时调用此方法回收，避免内存泄漏). <br/>
     *
     * @author askzhao
     */
    public void recycle() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    public void setImgSources(ArrayList<ImageView> nImgList) {
        mImgList = nImgList;
        notifyDataSetChanged();
    }

    /**
     * notifyDataSetChanged:(这里用一句话描述这个方法的作用). <br/>
     *
     * @author askzhao
     */
    public void notifyDataSetChanged() {

        if (mImgList != null && mImgList.size() > 0) {
            if (mImgList.size() != 1) {
                startFlipBanner();
            } else {
                recycle();
            }
            while (mImgViewList.size() < mImgList.size()) {
                ImageView imageView = new ImageView(mContext);
                imageView.setLayoutParams(new LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setImageResource(R.drawable.home_ad);
                mImgViewList.add(imageView);
                mViewFlipper.addView(imageView);
            }

            while (mImgViewList.size() > mImgList.size()) {
                mViewFlipper
                        .removeView(mImgViewList.get(mImgViewList.size() - 1));
                mImgViewList.remove(mImgViewList.size() - 1);
            }
            if (mImgList.size() != 1)
                while (dots.size() < mImgList.size()) {
                    // 添加 圆点标识
                    ImageView imageView_dot = new ImageView(mContext);
                    imageView_dot.setLayoutParams(new LayoutParams(10, 10));
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                            new ViewGroup.LayoutParams(
                                    LayoutParams.WRAP_CONTENT,
                                    LayoutParams.WRAP_CONTENT));
                    layoutParams.leftMargin = 10;
                    layoutParams.rightMargin = 10;
                    if (dots.size() == 0) {
                        imageView_dot.setBackgroundResource(page_focused);// R.drawable.page_focused
                    } else {
                        imageView_dot.setBackgroundResource(page_unfocused);// R.drawable.page_focused
                    }

                    dots.add(imageView_dot);
                    mDotLine.addView(imageView_dot, layoutParams);

                }
            if (mImgList.size() == 1) {
                mDotLine.setVisibility(View.GONE);
            } else {
                mDotLine.setVisibility(View.VISIBLE);
            }
            while (dots.size() > mImgList.size()) {
                // 删除 圆点标识
                mDotLine.removeView(dots.get(dots.size() - 1));
                dots.remove(dots.size() - 1);

            }
            for (int i = 0; i < mImgViewList.size(); i++) {
                ImageView imageView = mImgViewList.get(i);
//                ImageLoader.getInstance().displayImage(
//                        mImgList.get(i).getImage(), imageView,
//                        R.drawable.home_ad);
            }
        } else {
            mViewFlipper.removeAllViews();
        }

    }

    private float dertaY = 0;
    private float lastY = 0;
    private float dertaX = 0;
    private float lastX = 0;

    /*
     * (non-Javadoc) 避免父控件拦截touch事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dertaY = 0;
                lastY = ev.getY();
                dertaX = 0;
                lastX = ev.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                dertaY = ev.getY() - lastY;
                dertaX = ev.getX() - lastX;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            default:
                break;
        }

        if (Math.abs(dertaX) > Math.abs(dertaY)) {
            ViewParent parent = getParent();
            while (parent != null) {
                parent.requestDisallowInterceptTouchEvent(true);
                parent = parent.getParent();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

}
